package com.opensource.lzx.restartclient.netty.impl;

import com.opensource.lzx.restartclient.enums.NettyInstanceType;
import com.opensource.lzx.restartclient.netty.AbstractNettyInitService;
import com.opensource.lzx.restartclient.netty.handler.InitializedHandler;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class NioNettyClientImpl extends AbstractNettyInitService implements DisposableBean {
    private EventLoopGroup eventLoopGroup;

    private ChannelFuture channelFuture;

    @Override
    protected void doInit(String host, int port) {
        this.eventLoopGroup = new NioEventLoopGroup();

        super.bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.ALLOCATOR, ByteBufAllocator.DEFAULT)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new InitializedHandler());
        try {
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            log.info("Netty connect host:{} port:{} success.", host, port);
            this.channelFuture = channelFuture;

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("Netty connect server error, error msg: ", e);
            throw new RuntimeException(e);
        } finally {
            this.eventLoopGroup.shutdownGracefully();
        }
    }

    @Override
    public NettyInstanceType instanceType() {
        return NettyInstanceType.NIO;
    }

    @Override
    public void destroy() throws Exception {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            this.eventLoopGroup.shutdownGracefully();
            try {
                this.channelFuture.channel().closeFuture().sync();
            } catch (InterruptedException e) {
            }
        }));
    }
}
